package com.study.crypto.basic.digest;

import org.bouncycastle.pqc.crypto.gmss.util.GMSSUtil;

import java.math.BigInteger;

/**
 * @author Songjin
 * @since 2021-03-20 17:31
 * @deprecated 不建议使用了，请替换为 <code>com.study.crypto.basic.digest.SM3PublicKeyDigest</code>
 */
@Deprecated
public class SM3Digest extends org.bouncycastle.crypto.digests.SM3Digest {
    
    public void addId(BigInteger affineX, BigInteger affineY, byte[] id) {
        byte[] x = Util.asUnsigned32ByteArray(affineX);
        byte[] y = Util.asUnsigned32ByteArray(affineY);
        byte[] tmp = this.getSM2Za(x, y, id);
        if (x.length == 32 && y.length == 32) {
            this.reset();
            this.update(tmp, 0, tmp.length);
        } else {
            throw new IllegalArgumentException("参数有误");
        }
    }
    
    private byte[] getSM2Za(byte[] x, byte[] y, byte[] id) {
        GMSSUtil gmssUtil = new GMSSUtil();
        byte[] tmp = gmssUtil.intToBytesLittleEndian(id.length * 8);
        byte[] buffer = new byte[194 + id.length];
        buffer[0] = tmp[1];
        buffer[1] = tmp[0];
        byte[] a = Util.a;
        byte[] b = Util.b;
        byte[] gx = Util.Gx;
        byte[] gy = Util.Gy;
        int dPos = 2;
        System.arraycopy(id, 0, buffer, dPos, id.length);
        dPos = dPos + id.length;
        System.arraycopy(a, 0, buffer, dPos, 32);
        dPos += 32;
        System.arraycopy(b, 0, buffer, dPos, 32);
        dPos += 32;
        System.arraycopy(gx, 0, buffer, dPos, 32);
        dPos += 32;
        System.arraycopy(gy, 0, buffer, dPos, 32);
        dPos += 32;
        System.arraycopy(x, 0, buffer, dPos, 32);
        dPos += 32;
        System.arraycopy(y, 0, buffer, dPos, 32);
        dPos += 32;
        SM3Digest digest = new SM3Digest();
        digest.update(buffer, 0, buffer.length);
        byte[] out = new byte[32];
        digest.doFinal(out, 0);
        return out;
    }
}
